<?php
/**
 * 预定记录管理
 * 相对路径: adm/recs.php
 * 作者: 15058593138@qq.com
 */

// 查询记录
if (isset($_GET['act']) && $_GET['act'] === 'search') {
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : date('Ymd');
    $field = isset($_POST['field']) ? safeStr($_POST['field']) : 'usid';
    $keyword = isset($_POST['keyword']) ? safeStr($_POST['keyword']) : '';
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    
    $db = new DB();
    $db->autoCreateDateTable($date);
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    if (!$db->tableExists($recTable)) {
        jsonMsg(1, '查询成功', ['list' => [], 'total' => 0, 'page' => $page]);
    }
    
    // 构建查询条件
    $where = "1=1";
    if (!empty($keyword)) {
        $where .= " AND `{$field}` LIKE '%{$keyword}%'";
    }
    
    // 获取总数
    $sql = "SELECT COUNT(*) FROM `{$recTable}` WHERE {$where}";
    $total = $db->getCount($sql);
    
    // 查询数据
    $offset = ($page - 1) * PAGE_SIZE;
    $sql = "SELECT * FROM `{$recTable}` WHERE {$where} ORDER BY `atime` DESC LIMIT {$offset}, " . PAGE_SIZE;
    $list = $db->getAll($sql);
    
    // 获取教室和节次名称
    $rooms = readJson('./inc/weici.json.php');
    $roomNames = [];
    foreach ($rooms as $room) {
        $roomNames[$room['room']] = $room['name'];
    }
    
    $jiecis = readJson('./inc/jieci.json.php');
    $jieciNames = [];
    foreach ($jiecis as $jieci) {
        $jieciNames[$jieci['code']] = $jieci['name'];
    }
    
    foreach ($list as &$rec) {
        $rec['room_name'] = isset($roomNames[$rec['room']]) ? $roomNames[$rec['room']] : $rec['room'];
        $rec['jieci_name'] = isset($jieciNames[$rec['days']]) ? $jieciNames[$rec['days']] : $rec['days'];
        $rec['status_text'] = $rec['stats'] == 1 ? '有效' : ($rec['stats'] == 0 ? '已取消' : '已征用');
    }
    
    $db->close();
    jsonMsg(1, '查询成功', ['list' => $list, 'total' => $total, 'page' => $page]);
}

// 导出TSV
if (isset($_GET['act']) && $_GET['act'] === 'export') {
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : date('Ymd');
    
    $db = new DB();
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    if (!$db->tableExists($recTable)) {
        jsonMsg(0, '该日期无数据');
    }
    
    $sql = "SELECT * FROM `{$recTable}` ORDER BY `atime` DESC";
    $list = $db->getAll($sql);
    
    // 生成TSV
    $tsv = "学号\t教室\t日期\t节次\t座位\t核验码\t状态\t预定时间\n";
    foreach ($list as $rec) {
        $status = $rec['stats'] == 1 ? '有效' : ($rec['stats'] == 0 ? '已取消' : '已征用');
        $tsv .= "{$rec['usid']}\t{$rec['room']}\t{$rec['ijie']}\t{$rec['days']}\t{$rec['iwei']}\t{$rec['hema']}\t{$status}\t{$rec['atime']}\n";
    }
    
    $db->close();
    jsonMsg(1, '导出成功', ['tsv' => $tsv, 'filename' => "预定记录_{$date}.tsv"]);
}

require_once './inc/head.php';
?>

<div class="container">
    <div class="search-bar">
        <input type="date" id="searchDate" class="form-control" value="<?php echo date('Y-m-d'); ?>">
        <select id="searchField" class="form-control">
            <option value="usid">学号</option>
            <option value="room">教室</option>
            <option value="days">节次</option>
            <option value="hema">核验码</option>
        </select>
        <input type="text" id="searchKeyword" class="form-control" placeholder="输入关键词搜索">
        <button class="btn btn-primary" onclick="searchRecs(1)">查询</button>
        <button class="btn btn-success" onclick="exportRecs()">导出</button>
    </div>
    
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>学号</th>
                    <th>教室</th>
                    <th>日期</th>
                    <th>节次</th>
                    <th>座位</th>
                    <th>核验码</th>
                    <th>状态</th>
                    <th>预定时间</th>
                </tr>
            </thead>
            <tbody id="recsList">
                <tr>
                    <td colspan="8" style="text-align:center;">请选择日期查询</td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div id="pagination"></div>
</div>

<script>
    let currentPage = 1;
    
    // 搜索记录
    function searchRecs(page) {
        currentPage = page || 1;
        const date = document.getElementById('searchDate').value.replace(/-/g, '');
        const field = document.getElementById('searchField').value;
        const keyword = document.getElementById('searchKeyword').value;
        
        showLoading();
        ajax('admin.php?do=recs&act=search', {
            date: date,
            field: field,
            keyword: keyword,
            page: currentPage
        }, function(res) {
            hideLoading();
            if (res.code === 1) {
                renderRecs(res.data.list);
                renderPagination(res.data.total);
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 渲染记录列表
    function renderRecs(data) {
        const tbody = document.getElementById('recsList');
        
        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
            return;
        }
        
        let html = '';
        data.forEach(rec => {
            html += `<tr>
                <td>${rec.usid}</td>
                <td>${rec.room_name}</td>
                <td>${rec.ijie}</td>
                <td>${rec.jieci_name}</td>
                <td>${rec.iwei}号</td>
                <td>${rec.hema}</td>
                <td>
                    <span style="color:${rec.stats == 1 ? '#28a745' : (rec.stats == 0 ? '#999' : '#dc3545')}">
                        ${rec.status_text}
                    </span>
                </td>
                <td>${rec.atime}</td>
            </tr>`;
        });
        
        tbody.innerHTML = html;
    }
    
    // 渲染分页
    function renderPagination(total) {
        const paginationDiv = document.getElementById('pagination');
        paginationDiv.innerHTML = pagination(currentPage, total, 'searchRecs');
    }
    
    // 导出记录
    function exportRecs() {
        const date = document.getElementById('searchDate').value.replace(/-/g, '');
        
        showLoading();
        ajax('admin.php?do=recs&act=export', {date: date}, function(res) {
            hideLoading();
            if (res.code === 1) {
                // 下载TSV文件
                const blob = new Blob([res.data.tsv], {type: 'text/tab-separated-values;charset=utf-8;'});
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = res.data.filename;
                link.click();
                toast('导出成功', 'success');
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 页面加载时自动查询今天的记录
    window.onload = function() {
        searchRecs(1);
    };
    
    // 日期改变时自动查询
    document.getElementById('searchDate').onchange = function() {
        searchRecs(1);
    };
</script>

<?php require_once './inc/foot.php'; ?>